import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-17
 * Time: 08:27
 */
public class EchoClient {
    private final DatagramSocket socket;
    //这里的IP是String
    private final String severIP;
    private final int severPort;
    //传入服务器IP和端口
    public EchoClient(String severIP,int severPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.severIP = severIP;
        this.severPort = severPort;
    }
    //启动客户端
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner in = new Scanner(System.in);
        while (true){
            //提示用户要输入请求了
            System.out.print("-> ");
            //1.从控制台读取要发送的请求数据
            //在用户输入之前有阻塞效果
            if (!in.hasNext()){
                break;
            }
            String request = in.next();
            //2.请求并发送
            //字节数组，字节数组长度，服务器IP，服务器端口号
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(severIP),severPort);
            socket.send(requestPacket);
            //3.读取服务器返回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.将响应打印到控制台
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }
    //
    public static void main(String[] args) throws IOException {
        EchoClient client = new EchoClient("127.0.0.1",9090);
        client.start();
    }
}
